﻿using Prism.Commands;
using Prism.Dialogs;
using Prism.Mvvm;
using Rafy.Domain;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows.Controls;
using System.Windows.Input;

namespace Rafy.Book.ViewModels
{
    public class FmSubjectViewModel : BindableBase, IDialogAware
    {
        private string _subjectName;
        public string SubjectName
        {
            get => _subjectName;
            set => SetProperty(ref _subjectName, value);
        }

        private string _navText;
        public string NavText
        {
            get => _navText;
            set => SetProperty(ref _navText, value);
        }
        private List<ButtonOption> _buttons;
        public List<ButtonOption> Buttons
        {
            get => _buttons;
            set => SetProperty(ref _buttons, value);
        }

        public int? BookId { get; set; }

        public DelegateCommand SaveCommand { get; private set; }
        public FmSubjectViewModel()
        {
            SaveCommand = new DelegateCommand(SaveExcute);
        }

        private void LoadData()
        {
            Console.WriteLine("LoadData   bookid=" + BookId);
            if (BookId != null && BookId > 0)
            {
                var repo = RF.ResolveInstance<Base_BooksRepository>();
                var book = repo.GetById(BookId);
                SubjectName = book.F_BookName;
                NavText = book.F_NavPage;
            }
        }

        private void LoadButtons()
        {
            // 示例按钮，包含唯一Id和文本
            Console.WriteLine("LoadButtons   bookid=" + BookId);

            var repo = RF.ResolveInstance<Base_PublicButtonRepository>();
            var lst = repo.GetAll();
            if (BookId != null && BookId > 0)
            {
                var rp = RF.ResolveInstance<Base_ButtonRepository>();
                var btns = rp.GetsBy(BookId);
                var list = new List<ButtonOption>(); 
                foreach (var item in lst)
                {
                    var bit = btns.FirstOrDefault(e => e.F_BtnId == item.Id);
                    list.Add(new ButtonOption()
                    {
                        Id = item.Id,
                        Text = item.F_BtnInfo,
                        IsChecked = bit!=null
                    });
                }
                Buttons= list;
            }
            else
            {
                Buttons = lst.Select(s => new ButtonOption { Id = s.Id, Text = s.F_BtnInfo }).ToList();
            }
               
            
            
        }

        private void SaveExcute()
        {
            // 获取选中的按钮Id（例如：1,3,5）
            var selectedIds = string.Join(",", Buttons
                .Where(b => b.IsChecked)
                .Select(b => b.Id));

            var repo = RF.ResolveInstance<Base_BooksRepository>();
            var books = new Base_Books();
            if (BookId != null && BookId > 0)
            {
                books.Id = Convert.ToInt32(BookId);
                books.PersistenceStatus = PersistenceStatus.Modified;
            }
            books.F_BookName = SubjectName;
            books.F_NavPage = NavText;
            repo.Save(books);

            var newBtns = new Base_ButtonList();
            var rp = RF.ResolveInstance<Base_PublicButtonRepository>();
            var btns = rp.GetAll().Where(e => selectedIds.Contains(e.Id.ToString())).ToList();
            foreach (var item in btns)
            {
                newBtns.Add(new Base_Button()
                {
                    F_BtnName = item.F_BtnName,
                    F_NavPage = item.F_NavPage,
                    F_BooksId = books.Id,
                    F_BtnId = item.Id,
                    F_Prams = item.F_Prams
                });
            }
            var rpbtn = RF.ResolveInstance<Base_ButtonRepository>();
            if (BookId != null && BookId > 0)
            {
                var lst = rpbtn.GetsBy(BookId);
                lst.Clear();
                rpbtn.Save(lst);
            }
            rpbtn.Save(newBtns);

            RequestClose.Invoke(new DialogResult(ButtonResult.OK));
        }
        public DialogCloseListener RequestClose { get; }

        public string Title => "添加书本";

        //这个方法是允许关闭窗口
        public bool CanCloseDialog()
        {
            return true;
        }
        //关闭方法
        public void OnDialogClosed()
        {
            //RequestClose.Invoke(ButtonResult.Cancel);
            //MessageBox.Show("关闭窗口");
        }
        //打开之前传递过来的参数
        public void OnDialogOpened(IDialogParameters parameters)
        {
            //从上页面中传过来的参数
            BookId = parameters.GetValue<int?>("bookId");
            Console.WriteLine("bookid="+BookId);
            LoadData();
            LoadButtons();
        }
       
    }

    public class ButtonOption : BindableBase
    {
        public int Id { get; set; }

        private string _text;
        public string Text
        {
            get => _text;
            set => SetProperty(ref _text, value);
        }

        private bool _isChecked;
        public bool IsChecked
        {
            get => _isChecked;
            set => SetProperty(ref _isChecked, value);
        }
    }
}
